package com.shoubei.cashiedesk.constant;

import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.provider.Settings.Secure;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.shoubei.cashiedesk.base.App;
import com.shoubei.cashiedesk.utils.MVersionConfig;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Common {
	
	/**
	 * 未支付订单检测间隔时间
	 */
	public static final long PAYCHECK_OFFSETTIME = 3000L;
	
	/**
	 * 微信支付宝支付结果轮询检测间隔时间
	 */
	public static final long PAYRESULT_OFFSETTIME = 1000L;
	
	/**
	 * 阿里云消息轮询间隔时间
	 */
	public static final long POLLINGWAITTIME = 3000L;
	
	/**
	 * 会员卡循环读卡时间间隔
	 */
	public static final long CARDREADER_OFFSETTIME = 400L;

	/**
	 * 套餐自动合并
	 */
	public static final String SetMealAutoCombine = "setmeal_autocombine";

	/**
	 * 自动抹零方式（0：关闭 1：抹元 2：抹角 3：抹分）
	 */
	public static final String AutoZero_Type = "setmeal_autocombine";
	
	/**
	 * 阿里云消息开关
	 */
	public static final String ALIYUN_MESSAGE = "aliyun_message";
	
	
	/**
	 * 龙杰刷卡器卡状态广播
	 */
	public static final String ACTION_CARD_STATECHANGE = "com.android.liantuobank.CARD_STATECHANGE";

	/**
	 * 订单推送接收设置
	 */
	public static final class OrderAcceptState {
		
		/**
		 * 所有订单（true:接收 false:不接收）
		 */
		public static final String All_Order = "all_order";
		/**
		 * 商家外卖（true:接收 false:不接收）
		 */
		public static final String Merchant_Takeout = "merchant_takeout";
		/**
		 * 自助订单（true:接收 false:不接收）
		 */
		public static final String SelfHelp_Order = "selfhelp_order";
		/**
		 * 美团外卖（true:接收 false:不接收）
		 */
		public static final String MT_Takeout = "mt_takeout";
		/**
		 * 饿了么外卖（true:接收 false:不接收）
		 */
		public static final String ELE_Takeout = "ele_takeout";
		
		
		/**
		 * 所有的推送设置的key
		 */
		public static final String[] OrderAcceptKeyArr = new String[]{All_Order, Merchant_Takeout, SelfHelp_Order, MT_Takeout, ELE_Takeout};
	}
	
	/**   
	* 会员卡操作   
	*/
	public static final class CardReadState {
		public static final int FIND_CARD = 1001;
		public static final int WRITE_CARD = 1002;
		public static final int RESET_CARD = 1003;
	}

	/**
	 * false：不为空 true：为空
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNul(String str) {
		if (str == null || "".equals(str.trim()) || "null".equals(str.trim())) {
			return true;
		}
		return false;
	}

	/**
	 * 字符转浮点
	 * 
	 * @param str
	 * @return
	 */
	public static Float StringToFloat(String str) {
		if (str == null || "".equals(str) || "null".equals(str) || "Null".equals(str) || "NULL".equals(str)) {
			return 0.0f;
		}
		return Float.valueOf(str);
	}

	/**
	 * 字符转浮点
	 * 
	 * @param str
	 * @return
	 */
	public static int StringToInt(String str) {
		if (str == null || "".equals(str) || "null".equals(str) || "Null".equals(str) || "NULL".equals(str)) {
			return 0;
		}
		return Integer.valueOf(str);
	}

	public static Double StringToDouble(String str) {
		if (str == null || "".equals(str) || "null".equals(str) || "Null".equals(str) || "NULL".equals(str)) {
			return (double) 0;
		}
		return Double.valueOf(str);
	}

	public static boolean isNull(String str) {
		if (str == null || "".equals(str)) {
			return false;
		}
		return true;
	}

	/**
	 * 判断密码是否是数字和字母
	 * 
	 * @param pwd
	 * @return
	 */
	public static boolean isPwd(String pwd) {
		Pattern p = Pattern.compile("^(?=.*\\d.*)(?=.*[a-zA-Z].*).{6,}$");
		Matcher m = p.matcher(pwd);

		return m.matches();
	}

	/**
	 * 判断手机号码是否是13位
	 * 
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobile13(String mobiles) {
		if (mobiles != null && mobiles.length() == 11) {
			return true;
		}

		return false;
	}

	/**
	 * 判断email格式是否正确
	 * 
	 * @param email
	 * @return
	 */
	public static boolean isEmail(String email) {
		String str = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(email);

		return m.matches();
	}

	public static String uniqueId;

	/**
	 * 获取机器码
	 * 
	 * @param context
	 * @return
	 */
	public static String getDeviceID(Context context) {
		if (TextUtils.isEmpty(uniqueId)) {
			uniqueId = Secure.getString(App.getInstance().getContentResolver(), Secure.ANDROID_ID);
		}
		// TelephonyManager tm = (TelephonyManager)
		// context.getSystemService(Context.TELEPHONY_SERVICE);
		// String tmDevice, tmSerial, tmPhone, androidId;
		// tmDevice = "" + tm.getDeviceId();
		// tmSerial = "" + tm.getSimSerialNumber();
		// androidId = "" +
		// android.provider.Settings.Secure.getString(context.getContentResolver(),
		// android.provider.Settings.Secure.ANDROID_ID);
		// UUID deviceUuid = new UUID(androidId.hashCode(),
		// ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
		// String uniqueId = deviceUuid.toString();
		return uniqueId;
	}

	/**
	 * 获取应用版本号
	 * 
	 * @param context
	 * @return
	 */
	public static String getAppVersion(Context context) {
		String version = "";
		try {
			version = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS).versionName;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return version;
	}

	/**
	 * 补全桌号前面的0
	 * 
	 * @param number
	 * @param len
	 * @return
	 */
	public static String getDeskNumber(String number, int len) {
		int lenght = number.length();
		String zero = "0";
		for (int i = 0; i < len - lenght; i++) {
			number = zero + number;
		}
		return number;
	}

	public static String createJsonString(Object object) {
		String jsonString = "";
		try {
			jsonString = JSON.toJSONString(object);
		} catch (Exception e) {
		}

		return jsonString;
	}

	/**
	 * 判断是否是标准手机号
	 * 
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern.compile("^(?:13\\d|15[0-9]|14[0-9]|17[0-9]|18[0-9])-?\\d{5}(\\d{3}|\\*{3})$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	/**
	 * 隐藏手机号中间4位
	 * 
	 * @param mobile
	 * @return
	 */
	public static String hideMobile(String mobile) {
		if (!TextUtils.isEmpty(mobile) && isMobileNO(mobile) && mobile.length() == 11) {
			mobile = mobile.substring(0, 3) + "****" + mobile.substring(7, mobile.length());
		}
		return mobile;
	}

	/**
	 * 判断是否是正确的数字
	 * 
	 * @param obj
	 *            （.3其实为0.3 3.为3）
	 * @return true：是
	 */
	public static boolean judgeNumber(Object obj) {
		if (obj instanceof Integer) {
			return true;
		} else if (obj instanceof Double) {
			return true;
		} else if (obj instanceof Float) {
			return true;
		} else if (obj instanceof String) {
			try {
				Double.valueOf(obj.toString().trim());
				return true;
			} catch (Exception e) {
				return false;
			}
		} else {
			return false;
		}
	}

	/**
	 * 关闭Android导航栏，实现全屏
	 */
	public static void closeBar() {
		Log.e("CashierDesk", "关闭导航栏");
		// try {
		// String command;
		// command =
		// "LD_LIBRARY_PATH=/vendor/lib:/system/lib service call activity 42 s16 com.android.systemui";
		// ArrayList<String> envlist = new ArrayList<String>();
		// Map<String, String> env = System.getenv();
		// for (String envName : env.keySet()) {
		// envlist.add(envName + "=" + env.get(envName));
		// }
		// String[] envp = envlist.toArray(new String[0]);
		// Process proc = Runtime.getRuntime().exec(new String[] { "su", "-c",
		// command }, envp);
		// proc.waitFor();
		// } catch (Exception ex) {
		// Log.e("Cashier", "关闭导航栏失败：" + ex.getMessage());
		// // Toast.makeText(getApplicationContext(), ex.getMessage(),
		// // Toast.LENGTH_LONG).show();
		// }
	}

	/**
	 * 显示导航栏
	 */
	public static void showBar() {
		Log.e("CashierDesk", "显示导航栏");
		// try {
		// String command;
		// command =
		// "LD_LIBRARY_PATH=/vendor/lib:/system/lib am startservice -n com.android.systemui/.SystemUIService";
		// ArrayList<String> envlist = new ArrayList<String>();
		// Map<String, String> env = System.getenv();
		// for (String envName : env.keySet()) {
		// envlist.add(envName + "=" + env.get(envName));
		// }
		// String[] envp = envlist.toArray(new String[0]);
		// Process proc = Runtime.getRuntime().exec(new String[] { "su", "-c",
		// command }, envp);
		// proc.waitFor();
		// } catch (Exception e) {
		// Log.e("Cashier", "显示导航栏失败：" + e.getMessage());
		// e.printStackTrace();
		// }
	}

	/**
	 * 获取资源文件的字符串
	 * 
	 * @param id
	 * @return
	 */
	public static String getString(int id) {
		try {
			return App.getInstance().getResources().getString(id);
		} catch (Exception e) {
			// 看看到底国家化notfound到底是什么问题
			int mversion = App.getInstance().pre.getInt(MVersionConfig.mversionKey);
////			Bugtags.sendException(new Throwable("updateBegin:" + e.getMessage() + "\n" + "mversionKey:" + mversion + "," + MVersionConfig.getLocale()));
			MVersionConfig.updateMVersion();
//			Bugtags.sendException(new Throwable("updateEnd:" + e.getMessage() + "\n" + "mversionKey:" + mversion + "," + MVersionConfig.getLocale()));
		}
		return App.getInstance().getResources().getString(id);
	}

	/**
	 * 获取ip地址
	 * 
	 * @return
	 */
	public static String getHostIP() {
		String hostIp = null;
		try {
			Enumeration nis = NetworkInterface.getNetworkInterfaces();
			InetAddress ia = null;
			while (nis.hasMoreElements()) {
				NetworkInterface ni = (NetworkInterface) nis.nextElement();
				Enumeration<InetAddress> ias = ni.getInetAddresses();
				while (ias.hasMoreElements()) {
					ia = ias.nextElement();
					if (ia instanceof Inet6Address) {
						continue;// skip ipv6
					}
					String ip = ia.getHostAddress();
					if (!"127.0.0.1".equals(ip)) {
						hostIp = ia.getHostAddress();
						return hostIp;
					}
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
		return hostIp;
	}
	
	/**
	 * 如果double小数点后面为0，只保留整数
	 * @param count
	 * @return
	 */
	public static String doubleTrans(double count){
		String countStr = "";
		if (count % 1.0 == 0) {//如果小数点后是0，去掉0
			countStr = String.valueOf((long) count);
		}else{
			countStr = count + "";
		}
		return countStr;
	}

	/** 
     * 使用正则表达式提取中括号中的内容 
     * @param msg 
     * @return  
     */  
    public static List<String> extractMessageByRegular(String msg){
        List<String> list=new ArrayList<String>();
        Pattern p = Pattern.compile("\\([^(^)]*\\)");
        Matcher m = p.matcher(msg);
        while(m.find()){  
            list.add(m.group().substring(1, m.group().length()-1));  
        }  
        return list;  
    }  
    
    /**
	 * 使用正则表达式提取中括号中的内容并移除折扣备注（后厨备注不能显示折扣信息）
	 * 
	 * @param msg
	 * @return
	 */
    public static String getMessageByRegular(String msg) {
    	if(TextUtils.isEmpty(msg)){
    		return "";
    	}
    	if(!msg.contains("(")){//不包含()，比如H5下单备注不包含()
    		return msg;
    	}
		StringBuilder sb = new StringBuilder();
		Pattern p = Pattern.compile("\\([^(^)]*\\)");
		Matcher m = p.matcher(msg);
		while (m.find()) {
			String rmk = m.group().substring(1, m.group().length()-1);
        	if(!rmk.contains("%")){
        		sb.append(rmk);
        	}
		}
		return sb.toString();
	}
}
